package cn.gf.dimanagementchartdatatransfor.exceptions;

import cn.gf.dimanagementchartdatatransfor.entity.vo.common.ApiResponse;
import cn.gf.dimanagementchartdatatransfor.enums.ApiStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 数据库重复值异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public ApiResponse duplicateKeyException(DuplicateKeyException exception){
        log.error("数据库唯一值约束: {},{}",exception.getClass(),exception.getMessage());
        return ApiResponse.ofExceptionMsg("【数据库有重复值】",exception.getMessage());
    }

    /**
     * 自定义异常处理器
     * 使用例: throw new JsonException(Status.UNKNOWN_ERROR);
     */
    @ExceptionHandler(value = JsonException.class)
    @ResponseBody
    public ApiResponse jsonErrorHandler(JsonException exception) {
        log.error("[自定义异常]:{}", exception.getMessage());
        return ApiResponse.ofException(exception);
    }


    /**
     * 通用异常处理器
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResponse commonExceptionHandler(Exception exception){
        log.error("COMMON EXCEPTION: {},{}",exception.getClass(),exception.getMessage());
        return ApiResponse.ofExceptionMsg("【意外异常】",exception.getMessage());
    }
}
